package com.zgjl.api.util;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HttpSecurityRequestTool {

    private static final Logger LOGGER = Logger.getLogger(HttpSecurityRequestTool.class.getName());
    private static int connectTimeout = 5000;
    private static int readTimeout = 5000;
    public static String platformId = "";

    // 设置超时时间
    public static void setTimeouts(int connectTimeout, int readTimeout,String platformId) {
        HttpSecurityRequestTool.connectTimeout = connectTimeout;
        HttpSecurityRequestTool.readTimeout = readTimeout;
        HttpSecurityRequestTool.platformId = platformId;
    }

    // 通用HTTP请求方法
    public static ResultVO sendHttpRequest(String targetUrl, String method, String jsonData, Map<String, String> headers) throws HttpRequestException {
        HttpURLConnection connection = null;
        try {
            connection = createConnection(targetUrl, method, headers);
            if (jsonData != null && ("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method))) {
                writeRequestData(connection, SM4Util.encryptSM4(jsonData));
            }
            return getResponse(connection);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "HTTP request failed", e);
            throw new HttpRequestException("Failed to send HTTP request", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    // 创建连接并设置通用配置
    private static HttpURLConnection createConnection(String targetUrl, String method, Map<String, String> headers) throws Exception {
        URL url = new URL(targetUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setRequestProperty("Content-Type", "application/json");
        addHeaders(connection, headers);
        return connection;
    }

    // 添加自定义请求头
    private static void addHeaders(HttpURLConnection connection, Map<String, String> headers) {
        if (headers != null) {
            headers.forEach(connection::setRequestProperty);
        }
    }

    // 发送请求数据
    private static void writeRequestData(HttpURLConnection connection, String jsonData) throws Exception {
        connection.setDoOutput(true);
        try (OutputStream os = connection.getOutputStream()) {
            LOGGER.info("请求参数：" + jsonData);
            byte[] input = jsonData.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
    }

    // 获取响应数据
    private static ResultVO getResponse(HttpURLConnection connection) throws Exception {
        int responseCode = connection.getResponseCode();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(
                responseCode >= 200 && responseCode < 300 ? connection.getInputStream() : connection.getErrorStream(),
                StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            LOGGER.log(Level.INFO, "Response Code: " + responseCode);
            return JSONObject.parseObject(response.toString(), ResultVO.class);
        }
    }

    /**
     * @Descriptio: 平台post请求
     */
    public static ResultVO sendPostRequest(String targetUrl, String jsonData) throws HttpRequestException {
       return postRequest(targetUrl, jsonData, "");
    }

    /**
     * @Descriptio: post请求
     */
    public static ResultVO sendPostRequest(String targetUrl, String jsonData, String userId) throws HttpRequestException {
        return postRequest(targetUrl, jsonData, userId);
    }
    // 简化的POST请求方法
    private static ResultVO postRequest(String targetUrl, String jsonData, String userId) throws HttpRequestException {
        Map<String, String> headers = new HashMap<>();
        headers.put("ApiSecurity", "Bearer " + JWTUtil.createJWT(platformId+userId));
        return sendHttpRequest(targetUrl, "POST", jsonData, headers);
    }

    public static ResultVO sendGetRequest(String targetUrl) throws HttpRequestException {
       return sendGetRequest(targetUrl,"");
    }

    // 简化的GET请求方法
    public static ResultVO sendGetRequest(String targetUrl, String userId) throws HttpRequestException {
        Map<String, String> headers = new HashMap<>();
        headers.put("ApiSecurity", "Bearer " + JWTUtil.createJWT(platformId+userId));
        return sendHttpRequest(targetUrl, "GET", null, headers);
    }
}



